import store from '@/store';
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/home";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
  },
  {
    path: "/test",
    name: "test",
    component: () => import("../views/test"),
  },
  // 静态页面
  {
    path: "/about",
    name: "about",
    component: () => import("../views/about"),
  },
  {
    path: "/concat",
    name: "concat",
    component: () => import("../views/contact"),
  },
  {
    path: "/merchant",
    name: "merchant",
    component: () => import("../views/merchant"),
  },
  {
    path: "/task",
    name: "task",
    component: () => import("../views/task"),
  },
  {
    path: "/openPlatform",
    name: "openPlatform",
    component: () => import("../views/open-platform"),
  }
];

const router = new VueRouter({
  routes,
  mode: "history",
  scrollBehavior(to, from, savePosition) {
    return { x: 0, y: 0 }
  }
})

// 重写路由push方法
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return routerPush.call(this, location, onResolve, onReject)
  return routerPush.call(this, location).catch((error) => error)
}

// 设置路由拦截
router.beforeEach((to, from, next) => {
  const regex = /^\/user\b/
  const isMatch = regex.test(to.path)
  const hasPhone = store.getters['user/phone']
  if (isMatch && !hasPhone) {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router
